
/**
 * Script of the dialog "login to mikubook"
 */
var DialogConnectMikubook = new (function() {
	
	this.onclose = null;
	var $this = this;
	var success = false;
	
	/**
	 * When closing the dialog
	 */
	function onClose() {
		// If connected, we save login and password in settings
		if (success) {
			MikuClip.setOptions({
				login: $("#dialog-connect-mikubook-login").val(),
				password: $("#dialog-connect-mikubook-password").val()
			});
		}
		if (typeof($this.onclose) == "function") {
			$this.onclose();
		}
	}
	
	/**
	 * Show the dialog
	 */
	this.show = function(onclose) {
		$this.onclose = onclose;
		MikuClip.showDialog("#dialog-connect-mikubook");
	}
	
	
	/**
	 * On submit of the form
	 */
	function onSubmit() {
		$.mobile.loading('show');
		
		// Checking if login is correct
		$.ajax({
			url: MikuClip.URL.WEBSERVICE_LOGIN,
			data: {
				login: $("#dialog-connect-mikubook-login").val(),
				password: $("#dialog-connect-mikubook-password").val()
			},
			type: 'POST',
			success: onSubmitSuccess
		});
		return false;
	}
	
	/**
	 * Success of AJAX Request
	 */
	function onSubmitSuccess(data) {
		$.mobile.loading('hide');
		
		var o = JSON.parse(data);
		if (o.success) {
			success = true;
			$("#dialog-connect-mikubook").dialog('close');
		}
		else {
			$this.setError(o.error);
		}
	}
	
	/**
	 * When the dialog is showed
	 */
	function onShow() {
		$("#dialog-connect-mikubook-login").val(MikuClip.options.login);
	}
	
	/**
	 * After the dialog is showed, we focus the good elements
	 */
	function onAfterShow() {
		if ($("#dialog-connect-mikubook-login").val()) {
			$("#dialog-connect-mikubook-password").focus();
		}
		else {
			$("#dialog-connect-mikubook-login").focus();
		}
	}
	
	/**
	 * Set the error text displayed
	 */
	this.setError = function(error) {
		var text = WebappI18n.getItem("error.connection."+error);
		$("#dialog-connect-mikubook-error").html(text);
		$("#dialog-connect-mikubook-error").css("display", "block");

		if (error == "invalid_mail_password" || error == "password_too_long") {
			$("#dialog-connect-mikubook-password").val('');
			$("#dialog-connect-mikubook-password").focus();
		}
	}
	
	
	$("#dialog-connect-mikubook").on("pagebeforeshow", onShow);
	$("#dialog-connect-mikubook").on("pageshow", onAfterShow);
	$("#dialog-connect-mikubook").on("pagebeforehide", onClose);
	$("#btn-dialog-connect-mikubook-connect").on("click", onSubmit);
});